package com.alogic.json;

import com.anysoft.util.Factory;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.spi.JsonProvider;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JsonFactory
 *
 * @version 1.6.15.2 [20211103 duanyy] <br>
 * - 使用包内实现的JsonSmartJsonProvider类 <br>
 */
public class JsonFactory {
    protected static final Logger LOG = LoggerFactory.getLogger(JsonFactory.class);
    protected JsonProvider provider = null;
    protected boolean jsonpSupported = false;

    public JsonFactory(Properties props){
        jsonpSupported = PropertiesConstants.getBoolean(props,"http.jsonp",jsonpSupported);

        String module = PropertiesConstants.getString(props,"http.json.provider", JsonSmartJsonProvider.class.getName());
        Factory<JsonProvider> f = new Factory<JsonProvider>();
        try {
            provider = f.newInstance(module,props);
        }catch (Exception ex){
            provider = new JsonSmartJsonProvider();
            LOG.warn("Can not create instance of " + module);
            LOG.warn("Using default:" + provider.getClass().getName());
        }
    }

    public Object fromJsonString(String jsonString){
        return provider.parse(jsonString);
    }

    public String toJsonString(Object jsonObj){
        return provider.toJson(jsonObj);
    }

    public Object readJsonPath(Object jsonObj,String path){
        if (StringUtils.isNotEmpty(path)) {
            return JsonPath.read(jsonObj, path);
        }
        return null;
    }

    public String wrapJsonp(Properties ctx, String jsonString){
        if (jsonpSupported){
            String jsonp = PropertiesConstants.getString(ctx,"jsonp","");
            if (StringUtils.isNotEmpty(jsonp)){
                return  jsonp + "(" + jsonString + ")";
            }
        }
        return jsonString;
    }
}

